package cn.qiyu5522.service.impl;

import cn.qiyu5522.constant.SystemConstants;
import cn.qiyu5522.domain.VO.CategoryVO;
import cn.qiyu5522.domain.entity.Article;
import cn.qiyu5522.domain.entity.Category;
import cn.qiyu5522.domain.entity.ResponseResult;
import cn.qiyu5522.mapper.CategoryMapper;
import cn.qiyu5522.service.ArticleService;
import cn.qiyu5522.service.CategoryService;
import cn.qiyu5522.utils.BeanCopyUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 分类表 服务实现类
 * </p>
 *
 * @author Tonkey
 * @since 2024-04-10
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {


    @Resource
    private ArticleService articleService;
    @Resource
    private CategoryMapper categoryMapper;
    @Override
    public ResponseResult categoryList() {
        List<CategoryVO> categories = categoryMapper.selectNormalCategoryList();
        return ResponseResult.okResult(categories);
    }

    @Override
    public ResponseResult getCategoryList() {
        // 查询正常发布的文章表，返回它们的分类ID
        List<Article> articles = articleService.list(new LambdaQueryWrapper<Article>().eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL).select(Article::getCategoryId));
        // 分类ID去重
        Set<Long> collect = articles.stream().map(article -> article.getCategoryId()).collect(Collectors.toSet());
        // 根据分类ID查询分类表
        List<Category> categories = baseMapper.selectBatchIds(collect);
        // 过滤出状态启用的分类
        List<Category> categoryList = categories.stream().filter(category -> SystemConstants.STATUS_NORMAL.equals(category.getStatus())).collect(Collectors.toList());
        // 转成VO对象集合
        List<CategoryVO> categoryVOS = BeanCopyUtils.copyBeanList(categoryList, CategoryVO.class);
        return ResponseResult.okResult(categoryVOS);
    }


}
